package com.ytjj.common.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.enums.UsersStatusEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.exception.GlobalExceptionHandler;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisServiceImpl;
import com.ytjj.common.utils.AccountUtil;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 公共控制器
 *
 *
 * @version 1.0
 *
 */
@Controller
@Slf4j
public class BaseController extends GlobalExceptionHandler {

    @Resource
    private RedisServiceImpl redisService;

    /**
     * 获取登陆用户信息
     *
     * @return
     */
    public UsersResponse getCurrentUser(){
        String token = TokenUtil.getToken();
        if(StringUtil.isEmpty(token)){
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        String usesInfo = redisService.get(token);
        if(StringUtil.isEmpty(usesInfo)){
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        UsersResponse usersResponse = JSONObject.parseObject(usesInfo,UsersResponse.class);
        return usersResponse;
    }

    @Autowired
    private SysConfigUtil sysConfigUtil;

    /**
     * 获取登陆用户信息
     *
     * @return
     */
    public UsersResponse getH5CurrentUser(){
        String token = TokenUtil.getToken();
        if(StringUtil.isEmpty(token)){
            return null;
        }
        String sourcePlatform = TokenUtil.getSourcePlatform();
        String usesInfo = redisService.get(token);
        String reqSource = getSource();
        if(StringUtil.isEmpty(usesInfo)){
            if("h5".equals(reqSource) || "app".equals(reqSource) || "h5_2".equals(reqSource) || "h5_3".equals(reqSource)){
                UsersResponse usersResponse = new UsersResponse();
                usersResponse.setChannel(TokenUtil.getRequest().getHeader("channel"));
                usersResponse.setSource(reqSource);
                String account = AccountUtil.getRandomAccount();
                usersResponse.setAccount(account);
                usersResponse.setNickname("用户" + account);
                usersResponse.setToken(token);
                usersResponse.setStatus(UsersStatusEnums.unregister.getStatus());
                usersResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));
                if (StringUtils.isNotBlank(sourcePlatform)) {
                    String platform = sourcePlatform.toUpperCase() + "_SCORE";
                    String val = "";
                    try {
                        val = sysConfigUtil.getSysConfig(platform);
                    }catch (Exception e){

                    }
                    if (!StringUtils.isBlank(val)) {
                        usersResponse.setScore(Integer.valueOf(val));
                        usersResponse.setTotalScore(Integer.valueOf(val));
                    } else {
                        usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                        usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    }
                } else {
                    usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if(TokenUtil.getChannel().contains("ma-sms")){
                    // 短信的渠道最后一天过期
                    Calendar ca = Calendar.getInstance();
                    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(ca.getTime(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    // 其他渠道当天过期
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                usersResponse.setMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setLockMoney(new BigDecimal(0));
                usersResponse.setTotalMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setBrokerageNum(new BigDecimal(0));
                usersResponse.setFollow(0);
                usersResponse.setFans(0);
                usersResponse.setIsVip((byte) 0);
                usersResponse.setPraise(0);
                usersResponse.setDynamicSum(0);
                usersResponse.setVipMoney(0);
                usersResponse.setIsOpenLive((byte) 0);
                usersResponse.setIsZombie((byte) 0);
                usersResponse.setRegisterTime(new Date());
                usersResponse.setActivityMax(new BigDecimal(680));
                redisService.set(token, JSONObject.toJSONString(usersResponse));
                redisService.expire(token, TokenConstants.EXPIRE_SECONDS);
                return usersResponse;
            }
            return null;
        }
        UsersResponse usersResponse = JSONObject.parseObject(usesInfo,UsersResponse.class);
        return usersResponse;
    }


    /**
     * 获取登陆用户信息
     *
     * @return
     */
    public UsersResponse getH5CurrentUser(String sourcePlatform){
        String token = TokenUtil.getToken();
        log.info("根据sourcePlatform查询h5用户 token：{}",token);
        if(StringUtil.isEmpty(token)){
            return null;
        }
        String usesInfo = redisService.get(token);
        if(StringUtil.isEmpty(usesInfo)){
            if(PlatformConstant.PLATFORM_H5.equals(getSource()) || PlatformConstant.APP_PLATFORM.equals(getSource())
                    || PlatformConstant.H5_2_PLATFORM.equals(getSource())  || PlatformConstant.H5_3_PLATFORM.equals(getSource())){
                UsersResponse usersResponse = new UsersResponse();
                usersResponse.setChannel(TokenUtil.getRequest().getHeader("channel"));
                usersResponse.setSource(getSource());
                String account = AccountUtil.getRandomAccount();
                usersResponse.setAccount(account);
                usersResponse.setNickname("用户" + account);
                usersResponse.setToken(token);
                usersResponse.setStatus(UsersStatusEnums.unregister.getStatus());
                usersResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));

                if (StringUtils.isNotBlank(sourcePlatform)) {
                    String platform = sourcePlatform.toUpperCase() + "_SCORE";
                    if (sourcePlatform.equals("ssvip")) {
                        platform = sourcePlatform.toUpperCase() + "_NEW_SCORE";
                    }
                    log.info("根据sourcePlatform查询h5用户redis缓存积分 token：{},platform{}",token,platform);
                    String val = "";
                    try {
                        val = sysConfigUtil.getSysConfig(platform);
                    }catch (Exception e){

                    }
                    log.info("根据sourcePlatform查询h5用户redis缓存积分 token：{},val{}",token,val);
                    if (!StringUtils.isBlank(val)) {
                        usersResponse.setScore(Integer.valueOf(val));
                        usersResponse.setTotalScore(Integer.valueOf(val));
                    } else {
                        usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                        usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    }
                } else {
                    usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if("x".equals(sourcePlatform)
                        || "x2".equals(sourcePlatform)
                        || "svip".equals(sourcePlatform)
                        || "vip".equals(sourcePlatform)){
                    // 短信的渠道最后一天过期
                    Calendar ca = Calendar.getInstance();
                    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(ca.getTime(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    usersResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));
                }else{
                    // 其他渠道当天过期
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                usersResponse.setMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setLockMoney(new BigDecimal(0));
                usersResponse.setTotalMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setBrokerageNum(new BigDecimal(0));
                usersResponse.setFollow(0);
                usersResponse.setFans(0);
                usersResponse.setIsVip((byte) 0);
                usersResponse.setPraise(0);
                usersResponse.setDynamicSum(0);
                usersResponse.setVipMoney(0);
                usersResponse.setIsOpenLive((byte) 0);
                usersResponse.setIsZombie((byte) 0);
                usersResponse.setRegisterTime(new Date());
                usersResponse.setActivityMax(new BigDecimal(680));
                redisService.set(token, JSONObject.toJSONString(usersResponse));
                if("x".equals(sourcePlatform)
                        || "x2".equals(sourcePlatform)
                        || "svip".equals(sourcePlatform)
                        || "vip".equals(sourcePlatform)){
                    redisService.expire(token, TokenConstants.EXPIRE_SECONDS);
                }else{
                    redisService.expire(token, TokenConstants.EXPIRE_SECONDS_V2);
                }
                return usersResponse;
            }
            return null;
        }
        UsersResponse usersResponse = JSONObject.parseObject(usesInfo,UsersResponse.class);
        return usersResponse;
    }


    /**
     * 获取登陆用户信息
     *
     * @return
     */
    public UsersResponse getH5CurrentUser(String sourcePlatform, String token){
        if(StringUtil.isEmpty(token)){
            return null;
        }
        String usesInfo = redisService.get(token);
        if(StringUtil.isEmpty(usesInfo)){
            if("h5".equals(getSource())){
                UsersResponse usersResponse = new UsersResponse();
                usersResponse.setChannel(TokenUtil.getRequest().getHeader("channel"));
                usersResponse.setSource(getSource());
                String account = AccountUtil.getRandomAccount();
                usersResponse.setAccount(account);
                usersResponse.setNickname("用户" + account);
                usersResponse.setToken(token);
                usersResponse.setStatus(UsersStatusEnums.unregister.getStatus());
                usersResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));

                if (StringUtils.isNotBlank(sourcePlatform)) {
                    String platform = sourcePlatform.toUpperCase() + "_SCORE";
                    String val = "";
                    try {
                        val = sysConfigUtil.getSysConfig(platform);
                    }catch (Exception e){

                    }
                    if (!StringUtils.isBlank(val)) {
                        usersResponse.setScore(Integer.valueOf(val));
                        usersResponse.setTotalScore(Integer.valueOf(val));
                    } else {
                        usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                        usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    }
                } else {
                    usersResponse.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                    usersResponse.setTotalScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if("x".equals(sourcePlatform)
                        || "x2".equals(sourcePlatform)
                        || "svip".equals(sourcePlatform)
                        || "vip".equals(sourcePlatform)){
                    // 短信的渠道最后一天过期
                    Calendar ca = Calendar.getInstance();
                    ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(ca.getTime(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    usersResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));
                }else{
                    // 其他渠道当天过期
                    try {
                        Date date = sdf.parse(DateFormatUtils.format(new Date(), "yyyy-MM-dd 23:59:59"));
                        usersResponse.setBeforeDawnTime(date.getTime());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                usersResponse.setMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setLockMoney(new BigDecimal(0));
                usersResponse.setTotalMoney(new BigDecimal(sysConfigUtil.getSysConfig(SysConfigConstants.LOGIN_MONEY)));
                usersResponse.setBrokerageNum(new BigDecimal(0));
                usersResponse.setFollow(0);
                usersResponse.setFans(0);
                usersResponse.setIsVip((byte) 0);
                usersResponse.setPraise(0);
                usersResponse.setDynamicSum(0);
                usersResponse.setVipMoney(0);
                usersResponse.setIsOpenLive((byte) 0);
                usersResponse.setIsZombie((byte) 0);
                usersResponse.setRegisterTime(new Date());
                usersResponse.setActivityMax(new BigDecimal(680));
                redisService.set(token, JSONObject.toJSONString(usersResponse));
                if("x".equals(sourcePlatform)
                        || "x2".equals(sourcePlatform)
                        || "svip".equals(sourcePlatform)
                        || "vip".equals(sourcePlatform)){
                    redisService.expire(token, TokenConstants.EXPIRE_SECONDS);
                }else{
                    redisService.expire(token, TokenConstants.EXPIRE_SECONDS_V2);
                }
                return usersResponse;
            }
            return null;
        }
        UsersResponse usersResponse = JSONObject.parseObject(usesInfo,UsersResponse.class);
        return usersResponse;
    }

    /**
     * 获取来源
     *
     * @return
     */
    public String getSource(){
        return TokenUtil.getRequest().getHeader("source");
    }

    public String getImei(){
        return TokenUtil.getRequest().getHeader("imei");
    }

    public String getChildId(){
        return TokenUtil.getRequest().getHeader("childId");
    }

    /**
     * 获取推呀a_oId
     */
    public String getEffectAoId() {
        String token = TokenUtil.getToken();
        if (StringUtils.isBlank(token)) {
            return "";
        }
        String usesInfo = redisService.get(token);
        if (StringUtils.isNotBlank(usesInfo)) {
            UsersResponse usersResponse = JSONObject.parseObject(usesInfo, UsersResponse.class);
            if (StringUtils.isNotBlank(usersResponse.getAoId())) {
                return usersResponse.getAoId();
            }
        }
        return "";
    }
}
